import MonacoEditor, { type OnMount } from '@monaco-editor/react'
import { useComponetsStore } from '../../stores/components';
import { useEffect, useRef, useState } from 'react';
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons'

export function Source() {
    const editorRef = useRef(null);
    const containerRef = useRef(null);
    const [isFullscreen, setIsFullscreen] = useState(false);
    const {components} = useComponetsStore();

    const handleEditorMount: OnMount = (editor, monaco) => {
        editorRef.current = editor;
      editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyJ, () => {
          editor.getAction('editor.action.formatDocument')?.run()
      });
    }

    function toggleFullscreen() {
    if (!isFullscreen) {
      containerRef.current.requestFullscreen()
        .then(() => setIsFullscreen(true))
        .catch(err => {
          console.error(`Error attempting to enable fullscreen: ${err.message}`);
        });
    } else {
      document.exitFullscreen()
        .then(() => setIsFullscreen(false))
        .catch(err => {
          console.error(`Error attempting to exit fullscreen: ${err.message}`);
        });
    }
  }
  // 监听全屏变化事件（处理用户按ESC退出全屏的情况）
  useEffect(() => {
    function handleFullscreenChange() {
      setIsFullscreen(!!document.fullscreenElement);
    }
    
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);
    return <div className='h-[100%] relative' ref={containerRef}>
        <div onClick={toggleFullscreen}
        className="absolute right-3 top-3 z-10 p-2 rounded-md hover:bg-white text-gray-600 hover:text-gray-900 transition-all shadow-sm hover:shadow-md"
        aria-label={isFullscreen ? '退出全屏' : '全屏'}>
            { isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
        </div>
        <MonacoEditor
            ref={editorRef}
            height={'100%'}
            path='components.json'
            language='json'
            onMount={handleEditorMount}
            value={JSON.stringify(components, null, 2)}
            options={
                {
                    fontSize: 14,
                    scrollBeyondLastLine: false,
                    minimap: {
                    enabled: false,
                    },
                    scrollbar: {
                    verticalScrollbarSize: 6,
                    horizontalScrollbarSize: 6,
                    }
                }
            }
        />
    </div>
}
